<script setup>
import { ref, onMounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { userState, logout } from '../store.js'
import { clearAllReplies } from '../utils/clearReplies.js'

const router = useRouter()
const activeTab = ref('dashboard') // 当前激活的标签页
const searchQuery = ref('') // 搜索关键词
const filterStatus = ref('all') // 状态过滤

// 数据统计
const stats = ref({
  totalUsers: 0,
  totalPosts: 0,
  totalVideos: 0,
  totalComments: 0,
  totalMembers: 0
})

// 帖子数据
const allPosts = ref([])
const filteredPosts = computed(() => {
  let posts = [...allPosts.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    posts = posts.filter(post => 
      post.title.toLowerCase().includes(query) ||
      post.content.toLowerCase().includes(query) ||
      post.author.toLowerCase().includes(query)
    )
  }
  
  // 按时间排序（最新的在前）
  return posts.sort((a, b) => new Date(b.time) - new Date(a.time))
})

// 编辑帖子相关状态
const isEditModalVisible = ref(false)
const currentEditingPost = ref(null)
const editForm = ref({
  title: '',
  content: ''
})

// 创建帖子相关状态
const isCreateModalVisible = ref(false)
const createForm = ref({
  title: '',
  content: '',
  author: '管理员'
})

// 用户数据
const allUsers = ref([])
const userStatusFilter = ref('all') // 'all', 'active', 'inactive'
const userTypeFilter = ref('all') // 'all', 'member', 'non-member'

// 检测会员有效性
const checkMembershipValid = (user) => {
  if (!user.memberExpiry) return false
  return new Date(user.memberExpiry) > new Date()
}

const filteredUsers = computed(() => {
  let users = [...allUsers.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    users = users.filter(user => 
      user.username.toLowerCase().includes(query) ||
      user.email?.toLowerCase().includes(query) ||
      (user.isMember && '会员' === query)
    )
  }
  
  // 状态过滤
  if (userStatusFilter.value !== 'all') {
    users = users.filter(user => 
      userStatusFilter.value === 'active' ? user.isActive : !user.isActive
    )
  }
  
  // 会员类型过滤
  if (userTypeFilter.value !== 'all') {
    users = users.filter(user => {
      const isMember = checkMembershipValid(user)
      return userTypeFilter.value === 'member' ? isMember : !isMember
    })
  }
  
  return users
})

// 视频数据
const allVideos = ref([])
const filteredVideos = computed(() => {
  let videos = [...allVideos.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    videos = videos.filter(video => 
      video.title.toLowerCase().includes(query) ||
      video.description?.toLowerCase().includes(query)
    )
  }
  
  return videos
})

// 会员订单数据
const allMembershipOrders = ref([])
const filteredOrders = computed(() => {
  let orders = [...allMembershipOrders.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    orders = orders.filter(order => 
      order.userId.toLowerCase().includes(query) ||
      order.username?.toLowerCase().includes(query)
    )
  }
  
  return orders
})

// 评论数据
const allComments = ref([])
const filteredComments = computed(() => {
  let comments = [...allComments.value]
  
  // 搜索过滤
  if (searchQuery.value) {
    const query = searchQuery.value.toLowerCase()
    comments = comments.filter(comment => 
      comment.content.toLowerCase().includes(query) ||
      comment.author?.toLowerCase().includes(query) ||
      comment.postTitle?.toLowerCase().includes(query)
    )
  }
  
  // 按时间排序（最新的在前）
  return comments.sort((a, b) => new Date(b.time) - new Date(a.time))
})

// 检查是否为管理员，如果不是则重定向到登录页
onMounted(() => {
  if (!userState.isLoggedIn || !userState.userInfo.isAdmin) {
    router.push('/login')
  } else {
    loadAllData()
  }
})

// 加载所有数据
const loadAllData = () => {
  loadStats()
  loadPosts()
  loadUsers()
  loadVideos()
  loadMembershipOrders()
  loadComments()
}

// 加载统计数据
const loadStats = () => {
  try {
    // 获取用户总数
    const users = JSON.parse(localStorage.getItem('users') || '[]')
    stats.value.totalUsers = users.length
    stats.value.totalMembers = users.filter(user => user.isMember).length
    
    // 获取帖子总数（同时从posts和notes中读取，与loadPosts保持一致）
    const posts = JSON.parse(localStorage.getItem('posts') || '[]')
    const notes = JSON.parse(localStorage.getItem('notes') || '[]')
    const allContent = [...posts, ...notes]
    stats.value.totalPosts = allContent.length
    
    // 获取视频总数
    const videos = JSON.parse(localStorage.getItem('videos') || '[]')
    stats.value.totalVideos = videos.length
    
    // 计算评论总数
    let totalComments = 0
    allContent.forEach(post => {
      totalComments += post.replies || 0
    })
    stats.value.totalComments = totalComments
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 加载帖子数据
const loadPosts = () => {
  try {
    const posts = JSON.parse(localStorage.getItem('posts') || '[]')
    const notes = JSON.parse(localStorage.getItem('notes') || '[]')
    
    // 合并所有帖子来源
    const allContent = [...posts, ...notes]
    
    // 去重并添加ID（如果没有）
    const uniquePosts = []
    const seenIds = new Set()
    
    allContent.forEach(post => {
      if (!post.id) post.id = Date.now() + Math.random().toString(36).substr(2, 9)
      if (!seenIds.has(post.id)) {
        seenIds.add(post.id)
        uniquePosts.push(post)
      }
    })
    
    allPosts.value = uniquePosts
  } catch (error) {
    console.error('加载帖子数据失败:', error)
  }
}

// 加载用户数据
const loadUsers = () => {
  try {
    const users = JSON.parse(localStorage.getItem('users') || '[]')
    // 确保每个用户都有必要的字段
    allUsers.value = users.map(user => ({
      id: user.id || Date.now() + Math.random().toString(36).substr(2, 9),
      username: user.username || '未知用户',
      email: user.email || '',
      avatar: user.avatar || 'https://picsum.photos/200/200?random=user',
      isMember: user.isMember || false,
      memberExpiry: user.memberExpiry || null,
      isActive: user.isActive !== false, // 默认激活
      registerTime: user.registerTime || new Date().toISOString()
    }))
  } catch (error) {
    console.error('加载用户数据失败:', error)
  }
}

// 加载视频数据
const loadVideos = () => {
  try {
    const videos = JSON.parse(localStorage.getItem('videos') || '[]')
    allVideos.value = videos
  } catch (error) {
    console.error('加载视频数据失败:', error)
  }
}

// 加载会员订单数据
const loadMembershipOrders = () => {
  try {
    const orders = JSON.parse(localStorage.getItem('membershipOrders') || '[]')
    allMembershipOrders.value = orders
  } catch (error) {
    console.error('加载会员订单数据失败:', error)
  }
}

// 加载评论数据
const loadComments = () => {
  try {
    const comments = []
    const allPosts = JSON.parse(localStorage.getItem('posts') || '[]')
    const allNotes = JSON.parse(localStorage.getItem('notes') || '[]')
    
    // 从posts中提取评论
    allPosts.forEach(post => {
      if (post.comments && Array.isArray(post.comments)) {
        post.comments.forEach(comment => {
          comments.push({
            id: comment.id || Date.now() + Math.random().toString(36).substr(2, 9),
            content: comment.content,
            author: comment.author || '匿名用户',
            time: comment.time || new Date().toISOString(),
            postId: post.id,
            postTitle: post.title,
            source: 'post'
          })
        })
      }
    })
    
    // 从notes中提取评论
    allNotes.forEach(note => {
      if (note.comments && Array.isArray(note.comments)) {
        note.comments.forEach(comment => {
          comments.push({
            id: comment.id || Date.now() + Math.random().toString(36).substr(2, 9),
            content: comment.content,
            author: comment.author || '匿名用户',
            time: comment.time || new Date().toISOString(),
            postId: note.id,
            postTitle: note.title,
            source: 'note'
          })
        })
      }
    })
    
    allComments.value = comments
  } catch (error) {
    console.error('加载评论数据失败:', error)
  }
}

// 删除帖子
const deletePost = (postId) => {
  if (confirm('确定要删除这个帖子吗？此操作不可恢复！')) {
    try {
      // 从allPosts中移除
      allPosts.value = allPosts.value.filter(post => post.id !== postId)
      
      // 更新localStorage中的posts
      const posts = JSON.parse(localStorage.getItem('posts') || '[]')
      const updatedPosts = posts.filter(post => post.id !== postId)
      localStorage.setItem('posts', JSON.stringify(updatedPosts))
      
      // 更新localStorage中的notes
      const notes = JSON.parse(localStorage.getItem('notes') || '[]')
      const updatedNotes = notes.filter(note => note.id !== postId)
      localStorage.setItem('notes', JSON.stringify(updatedNotes))
      
      alert('帖子删除成功！')
      loadStats() // 重新加载统计数据
    } catch (error) {
      console.error('删除帖子失败:', error)
      alert('删除失败，请重试！')
    }
  }
}

// 打开编辑帖子模态框
const openEditModal = (post) => {
  currentEditingPost.value = { ...post }
  editForm.value = {
    title: post.title || '',
    content: post.content || ''
  }
  isEditModalVisible.value = true
}

// 保存编辑后的帖子
const saveEditedPost = () => {
  if (!editForm.value.title.trim()) {
    alert('标题不能为空！')
    return
  }
  
  try {
    // 更新内存中的帖子数据
    const postIndex = allPosts.value.findIndex(p => p.id === currentEditingPost.value.id)
    if (postIndex !== -1) {
      allPosts.value[postIndex] = {
        ...allPosts.value[postIndex],
        title: editForm.value.title,
        content: editForm.value.content
      }
    }
    
    // 更新localStorage中的posts
    let posts = JSON.parse(localStorage.getItem('posts') || '[]')
    const postIndexInStorage = posts.findIndex(p => p.id === currentEditingPost.value.id)
    if (postIndexInStorage !== -1) {
      posts[postIndexInStorage] = {
        ...posts[postIndexInStorage],
        title: editForm.value.title,
        content: editForm.value.content
      }
      localStorage.setItem('posts', JSON.stringify(posts))
    }
    
    // 检查并更新localStorage中的notes
    let notes = JSON.parse(localStorage.getItem('notes') || '[]')
    const noteIndexInStorage = notes.findIndex(p => p.id === currentEditingPost.value.id)
    if (noteIndexInStorage !== -1) {
      notes[noteIndexInStorage] = {
        ...notes[noteIndexInStorage],
        title: editForm.value.title,
        content: editForm.value.content
      }
      localStorage.setItem('notes', JSON.stringify(notes))
    }
    
    alert('帖子编辑成功！')
    closeEditModal()
  } catch (error) {
    console.error('编辑帖子失败:', error)
    alert('编辑失败，请重试！')
  }
}

// 关闭编辑模态框
const closeEditModal = () => {
  isEditModalVisible.value = false
  currentEditingPost.value = null
  editForm.value = {
    title: '',
    content: ''
  }
}

// 打开创建帖子模态框
const openCreateModal = () => {
  createForm.value = {
    title: '',
    content: '',
    author: '管理员'
  }
  isCreateModalVisible.value = true
}

// 创建新帖子
const createNewPost = () => {
  if (!createForm.value.title.trim()) {
    alert('标题不能为空！')
    return
  }
  
  try {
    const newPost = {
      id: Date.now() + Math.random().toString(36).substr(2, 9),
      title: createForm.value.title,
      content: createForm.value.content,
      author: createForm.value.author,
      time: new Date().toISOString(),
      views: 0,
      replies: 0,
      likes: 0
    }
    
    // 添加到内存中的帖子数据
    allPosts.value.unshift(newPost)
    
    // 添加到localStorage
    const posts = JSON.parse(localStorage.getItem('posts') || '[]')
    posts.unshift(newPost)
    localStorage.setItem('posts', JSON.stringify(posts))
    
    alert('帖子创建成功！')
    closeCreateModal()
    loadStats() // 重新加载统计数据
  } catch (error) {
    console.error('创建帖子失败:', error)
    alert('创建失败，请重试！')
  }
}

// 关闭创建模态框
const closeCreateModal = () => {
  isCreateModalVisible.value = false
  createForm.value = {
    title: '',
    content: '',
    author: '管理员'
  }
}

// 禁用/启用用户
const toggleUserStatus = (userId, isActive) => {
  const action = isActive ? '禁用' : '启用'
  if (confirm(`确定要${action}这个用户吗？`)) {
    try {
      // 更新内存中的用户数据
      const user = allUsers.value.find(u => u.id === userId)
      if (user) {
        user.isActive = !isActive
      }
      
      // 更新localStorage
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      const updatedUsers = users.map(u => 
        u.id === userId ? { ...u, isActive: !isActive } : u
      )
      localStorage.setItem('users', JSON.stringify(updatedUsers))
      
      alert(`用户${action}成功！`)
    } catch (error) {
      console.error(`${action}用户失败:`, error)
      alert(`${action}失败，请重试！`)
    }
  }
}

// 设置/取消会员
const toggleUserMembership = (userId, isMember) => {
  const action = isMember ? '取消会员' : '设置会员'
  if (confirm(`确定要${action}这个用户吗？`)) {
    try {
      // 更新内存中的用户数据
      const user = allUsers.value.find(u => u.id === userId)
      if (user) {
        user.isMember = !isMember
        if (!isMember) {
          // 设置会员有效期为30天后
          const expiryDate = new Date()
          expiryDate.setDate(expiryDate.getDate() + 30)
          user.memberExpiry = expiryDate.toISOString()
        } else {
          user.memberExpiry = null
        }
      }
      
      // 更新localStorage
      const users = JSON.parse(localStorage.getItem('users') || '[]')
      const updatedUsers = users.map(u => {
        if (u.id === userId) {
          return {
            ...u,
            isMember: !isMember,
            memberExpiry: !isMember ? new Date(Date.now() + 30 * 24 * 60 * 60 * 1000).toISOString() : null
          }
        }
        return u
      })
      localStorage.setItem('users', JSON.stringify(updatedUsers))
      
      alert(`${action}成功！`)
      loadStats() // 重新加载统计数据
    } catch (error) {
      console.error(`${action}失败:`, error)
      alert(`${action}失败，请重试！`)
    }
  }
}

// 删除视频
const deleteVideo = (videoId) => {
  if (confirm('确定要删除这个视频吗？此操作不可恢复！')) {
    try {
      // 从allVideos中移除
      allVideos.value = allVideos.value.filter(video => video.id !== videoId)
      
      // 更新localStorage
      const videos = JSON.parse(localStorage.getItem('videos') || '[]')
      const updatedVideos = videos.filter(video => video.id !== videoId)
      localStorage.setItem('videos', JSON.stringify(updatedVideos))
      
      alert('视频删除成功！')
      loadStats() // 重新加载统计数据
    } catch (error) {
      console.error('删除视频失败:', error)
      alert('删除失败，请重试！')
    }
  }
}

// 删除评论
const deleteComment = (commentId) => {
  if (confirm('确定要删除这条评论吗？此操作不可恢复！')) {
    try {
      // 找到要删除的评论
      const commentToDelete = allComments.value.find(c => c.id === commentId)
      if (!commentToDelete) {
        alert('评论不存在！')
        return
      }
      
      // 从内存中移除评论
      allComments.value = allComments.value.filter(c => c.id !== commentId)
      
      // 根据来源更新相应的localStorage数据
      if (commentToDelete.source === 'post') {
        const posts = JSON.parse(localStorage.getItem('posts') || '[]')
        const updatedPosts = posts.map(post => {
          if (post.id === commentToDelete.postId && post.comments) {
            post.comments = post.comments.filter(c => c.id !== commentId)
            // 更新回复数
            post.replies = (post.replies || 0) - 1
          }
          return post
        })
        localStorage.setItem('posts', JSON.stringify(updatedPosts))
      } else if (commentToDelete.source === 'note') {
        const notes = JSON.parse(localStorage.getItem('notes') || '[]')
        const updatedNotes = notes.map(note => {
          if (note.id === commentToDelete.postId && note.comments) {
            note.comments = note.comments.filter(c => c.id !== commentId)
            // 更新回复数
            if (note.replies) note.replies--
          }
          return note
        })
        localStorage.setItem('notes', JSON.stringify(updatedNotes))
      }
      
      alert('评论删除成功！')
      loadStats() // 重新加载统计数据
      loadComments() // 重新加载评论数据
    } catch (error) {
      console.error('删除评论失败:', error)
      alert('删除失败，请重试！')
    }
  }
}

// 清空所有帖子回复
const handleClearReplies = () => {
  if (confirm('确定要清空所有帖子的回复吗？此操作不可恢复！')) {
    const success = clearAllReplies()
    if (success) {
      alert('所有帖子回复已成功清除！')
      loadStats() // 重新加载统计数据
    } else {
      alert('清除失败，请重试！')
    }
  }
}

// 清空所有数据
const handleClearAllData = () => {
  if (confirm('确定要清空所有数据吗？此操作不可恢复！')) {
    try {
      // 清空所有本地存储数据
      const keysToClear = ['posts', 'notes', 'users', 'videos', 'userPosts', 'postReplies', 'comments', 'replies', 'membershipOrders']
      keysToClear.forEach(key => {
        localStorage.removeItem(key)
      })
      alert('所有数据已成功清空！')
      loadAllData() // 重新加载所有数据
    } catch (error) {
      console.error('清空数据失败:', error)
      alert('清空失败，请重试！')
    }
  }
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return '未知'
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN')
}

// 退出登录
const handleLogout = async () => {
  try {
    await logout()
    router.push('/login')
  } catch (error) {
    console.error('退出登录失败:', error)
  }
}

// 重置搜索
const resetSearch = () => {
  searchQuery.value = ''
  filterStatus.value = 'all'
  userStatusFilter.value = 'all'
  userTypeFilter.value = 'all'
}

// 切换标签页
const switchTab = (tab) => {
  activeTab.value = tab
  resetSearch() // 切换标签时重置搜索和过滤
}</script>

<template>
  <div class="admin-view">
    <header class="admin-header">
      <h1>管理后台</h1>
      <div class="admin-info">
        <span>欢迎您，{{ userState.userInfo.username }}</span>
        <button class="logout-btn" @click="handleLogout">退出登录</button>
      </div>
    </header>
    
    <!-- 导航菜单 -->
    <nav class="admin-nav">
      <ul class="nav-tabs">
        <li 
          :class="['nav-tab', { active: activeTab === 'dashboard' }]" 
          @click="switchTab('dashboard')"
        >
          <span class="tab-icon">📊</span>
          <span class="tab-text">控制面板</span>
        </li>
        <li 
          :class="['nav-tab', { active: activeTab === 'posts' }]" 
          @click="switchTab('posts')"
        >
          <span class="tab-icon">📝</span>
          <span class="tab-text">帖子管理</span>
        </li>
        <li 
          :class="['nav-tab', { active: activeTab === 'users' }]" 
          @click="switchTab('users')"
        >
          <span class="tab-icon">👥</span>
          <span class="tab-text">用户管理</span>
        </li>
        <li 
          :class="['nav-tab', { active: activeTab === 'videos' }]" 
          @click="switchTab('videos')"
        >
          <span class="tab-icon">📹</span>
          <span class="tab-text">视频管理</span>
        </li>
        <li 
          :class="['nav-tab', { active: activeTab === 'membership' }]" 
          @click="switchTab('membership')"
        >
          <span class="tab-icon">💎</span>
          <span class="tab-text">会员管理</span>
        </li>
        <li 
          :class="['nav-tab', { active: activeTab === 'comments' }]" 
          @click="switchTab('comments')"
        >
          <span class="tab-icon">💬</span>
          <span class="tab-text">评论管理</span>
        </li>
        <li 
          :class="['nav-tab', { active: activeTab === 'operations' }]" 
          @click="switchTab('operations')"
        >
          <span class="tab-icon">⚙️</span>
          <span class="tab-text">系统操作</span>
        </li>
      </ul>
    </nav>
    
    <main class="admin-content">
      <!-- 搜索和过滤区 -->
      <div v-if="activeTab !== 'dashboard' && activeTab !== 'operations'" class="search-filter">
        <input 
          type="text" 
          v-model="searchQuery" 
          placeholder="搜索..."
          class="search-input"
        >
        
        <!-- 用户管理特有过滤 -->
        <div v-if="activeTab === 'users'" class="filter-group">
          <label>用户状态：</label>
          <select v-model="filterStatus" class="filter-select">
            <option value="all">全部用户</option>
            <option value="member">会员用户</option>
            <option value="non-member">普通用户</option>
          </select>
        </div>
      </div>
      
      <!-- 控制面板 -->
      <div v-if="activeTab === 'dashboard'" class="dashboard-content">
        <!-- 统计信息卡片 -->
        <section class="stats-section">
          <h2>系统统计</h2>
          <div class="stats-grid">
            <div class="stat-card clickable-box" @click="switchTab('users')">
              <div class="stat-icon">👥</div>
              <div class="stat-content">
                <h3>{{ stats.totalUsers }}</h3>
                <p>用户总数</p>
              </div>
            </div>
            <div class="stat-card clickable-box" @click="switchTab('posts')">
              <div class="stat-icon">📝</div>
              <div class="stat-content">
                <h3>{{ stats.totalPosts }}</h3>
                <p>帖子总数</p>
              </div>
            </div>
            <div class="stat-card clickable-box" @click="switchTab('videos')">
              <div class="stat-icon">📹</div>
              <div class="stat-content">
                <h3>{{ stats.totalVideos }}</h3>
                <p>视频总数</p>
              </div>
            </div>
            <div class="stat-card clickable-box">
              <div class="stat-icon">💬</div>
              <div class="stat-content">
                <h3>{{ stats.totalComments }}</h3>
                <p>评论总数</p>
              </div>
            </div>
            <div class="stat-card clickable-box" @click="switchTab('membership')">
              <div class="stat-icon">💎</div>
              <div class="stat-content">
                <h3>{{ stats.totalMembers }}</h3>
                <p>会员总数</p>
              </div>
            </div>
          </div>
        </section>
        
        <!-- 系统信息 -->
        <section class="system-info">
          <h2>系统信息</h2>
          <div class="info-box clickable-box">
            <p><strong>当前版本：</strong>v1.0.0</p>
            <p><strong>运行环境：</strong>开发环境</p>
            <p><strong>管理员：</strong>{{ userState.userInfo.username }}</p>
            <p><strong>登录时间：</strong>{{ new Date().toLocaleString('zh-CN') }}</p>
            <p><strong>系统时间：</strong>{{ new Date().toLocaleString('zh-CN') }}</p>
          </div>
        </section>
      </div>
      
      <!-- 帖子管理 -->
      <div v-if="activeTab === 'posts'" class="posts-content">
        <div class="section-header">
          <h2>帖子管理</h2>
          <button class="action-btn-sm primary" @click="openCreateModal">创建新帖子</button>
        </div>
        <div class="data-table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>标题</th>
                <th>作者</th>
                <th>发布时间</th>
                <th>浏览量</th>
                <th>回复数</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="post in filteredPosts" :key="post.id">
                <td>{{ post.id.slice(-8) }}</td>
                <td class="post-title">{{ post.title }}</td>
                <td>{{ post.author }}</td>
                <td>{{ formatDate(post.time) }}</td>
                <td>{{ post.views || 0 }}</td>
                <td>{{ post.replies || 0 }}</td>
                <td>
                  <button class="action-btn-sm primary" @click="openEditModal(post)">编辑</button>
                  <button class="action-btn-sm danger" @click="deletePost(post.id)">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
          <div v-if="filteredPosts.length === 0" class="empty-state">
            暂无帖子数据
          </div>
        </div>
      </div>
      
      <!-- 用户管理 -->
      <div v-if="activeTab === 'users'" class="users-content">
        <h2>用户管理</h2>
        <div class="search-filter">
          <div class="filter-group">
            <label>账户状态:</label>
            <select v-model="userStatusFilter" class="filter-select">
              <option value="all">全部</option>
              <option value="active">启用</option>
              <option value="inactive">禁用</option>
            </select>
          </div>
          <div class="filter-group">
            <label>会员类型:</label>
            <select v-model="userTypeFilter" class="filter-select">
              <option value="all">全部</option>
              <option value="member">会员</option>
              <option value="non-member">非会员</option>
            </select>
          </div>
        </div>
        <div class="data-table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>用户名</th>
                <th>邮箱</th>
                <th>会员状态</th>
                <th>会员到期</th>
                <th>账号状态</th>
                <th>注册时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="user in filteredUsers" :key="user.id">
                <td>{{ user.id.slice(-8) }}</td>
                <td>{{ user.username }}</td>
                <td>{{ user.email || '未设置' }}</td>
                <td>
                    <span :class="['status-badge', { 'member': checkMembershipValid(user) }]">
                      {{ checkMembershipValid(user) ? '有效会员' : user.isMember ? '过期会员' : '普通' }}
                    </span>
                  </td>
                <td>{{ user.memberExpiry ? formatDate(user.memberExpiry) : '无' }}</td>
                <td>
                  <span :class="['status-badge', { 'active': user.isActive, 'inactive': !user.isActive }]">
                    {{ user.isActive ? '激活' : '禁用' }}
                  </span>
                </td>
                <td>{{ formatDate(user.registerTime) }}</td>
                <td>
                  <button 
                    :class="['action-btn-sm', user.isActive ? 'danger' : 'success']" 
                    @click="toggleUserStatus(user.id, user.isActive)"
                  >
                    {{ user.isActive ? '禁用' : '启用' }}
                  </button>
                  <button 
                    :class="['action-btn-sm', user.isMember ? 'warning' : 'primary']" 
                    @click="toggleUserMembership(user.id, user.isMember)"
                  >
                    {{ user.isMember ? '取消会员' : '设为会员' }}
                  </button>
                </td>
              </tr>
            </tbody>
          </table>
          <div v-if="filteredUsers.length === 0" class="empty-state">
            暂无用户数据
          </div>
        </div>
      </div>
      
      <!-- 视频管理 -->
      <div v-if="activeTab === 'videos'" class="videos-content">
        <h2>视频管理</h2>
        <div class="data-table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>标题</th>
                <th>观看次数</th>
                <th>点赞数</th>
                <th>发布日期</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="video in filteredVideos" :key="video.id">
                <td>{{ video.id }}</td>
                <td class="video-title">{{ video.title }}</td>
                <td>{{ video.views || 0 }}</td>
                <td>{{ video.likes || 0 }}</td>
                <td>{{ video.publishDate || '未知' }}</td>
                <td>
                  <button class="delete-btn" @click="deleteVideo(video.id)">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
          <div v-if="filteredVideos.length === 0" class="empty-state">
            暂无视频数据
          </div>
        </div>
      </div>
      
      <!-- 会员管理 -->
      <div v-if="activeTab === 'membership'" class="membership-content">
        <h2>会员管理</h2>
        
        <section class="members-list">
          <h3>会员用户列表</h3>
          <div class="data-table-wrapper">
            <table class="data-table">
              <thead>
                <tr>
                  <th>ID</th>
                  <th>用户名</th>
                  <th>会员到期时间</th>
                  <th>注册时间</th>
                  <th>操作</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="user in filteredUsers.filter(u => u.isMember)" :key="user.id">
                  <td>{{ user.id.slice(-8) }}</td>
                  <td>{{ user.username }}</td>
                  <td>{{ formatDate(user.memberExpiry) }}</td>
                  <td>{{ formatDate(user.registerTime) }}</td>
                  <td>
                    <button class="action-btn-sm warning" @click="toggleUserMembership(user.id, user.isMember)">
                      取消会员
                    </button>
                  </td>
                </tr>
              </tbody>
            </table>
            <div v-if="filteredUsers.filter(u => u.isMember).length === 0" class="empty-state">
              暂无会员用户
            </div>
          </div>
        </section>
        
        <section class="orders-list">
          <h3>会员订单记录</h3>
          <div class="data-table-wrapper">
            <table class="data-table">
              <thead>
                <tr>
                  <th>订单ID</th>
                  <th>用户ID</th>
                  <th>用户名</th>
                  <th>订单金额</th>
                  <th>订单时间</th>
                  <th>状态</th>
                </tr>
              </thead>
              <tbody>
                <tr v-for="order in filteredOrders" :key="order.id">
                  <td>{{ order.id || '未知' }}</td>
                  <td>{{ order.userId.slice(-8) }}</td>
                  <td>{{ order.username || '未知' }}</td>
                  <td>¥{{ order.amount || 0 }}</td>
                  <td>{{ formatDate(order.createdAt) }}</td>
                  <td>
                    <span class="status-badge success">{{ order.status || '已支付' }}</span>
                  </td>
                </tr>
              </tbody>
            </table>
            <div v-if="filteredOrders.length === 0" class="empty-state">
              暂无订单记录
            </div>
          </div>
        </section>
      </div>
      
      <!-- 评论管理 -->
      <div v-if="activeTab === 'comments'" class="comments-content">
        <h2>评论管理</h2>
        <div class="data-table-wrapper">
          <table class="data-table">
            <thead>
              <tr>
                <th>ID</th>
                <th>内容</th>
                <th>作者</th>
                <th>所属帖子</th>
                <th>评论时间</th>
                <th>操作</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="comment in filteredComments" :key="comment.id">
                <td>{{ comment.id.slice(-8) }}</td>
                <td class="comment-content">{{ comment.content }}</td>
                <td>{{ comment.author }}</td>
                <td class="post-title">{{ comment.postTitle }}</td>
                <td>{{ formatDate(comment.time) }}</td>
                <td>
                  <button class="action-btn-sm danger" @click="deleteComment(comment.id)">删除</button>
                </td>
              </tr>
            </tbody>
          </table>
          <div v-if="filteredComments.length === 0" class="empty-state">
            暂无评论数据
          </div>
        </div>
      </div>
      
      <!-- 系统操作 -->
      <div v-if="activeTab === 'operations'" class="operations-content">
        <h2>系统操作</h2>
        <div class="operations-grid">
          <button class="action-btn clickable-box danger" @click="handleClearReplies">
            <div class="action-icon">🗑️</div>
            <span>清空所有帖子回复</span>
          </button>
          <button class="action-btn clickable-box warning" @click="handleClearAllData">
            <div class="action-icon">⚠️</div>
            <span>清空所有数据</span>
          </button>
          <button class="action-btn clickable-box primary" @click="loadAllData">
            <div class="action-icon">🔄</div>
            <span>刷新所有数据</span>
          </button>
        </div>
      </div>
    </main>
    
    <!-- 编辑帖子模态框 -->
            <div v-if="isEditModalVisible" class="modal-overlay" @click="closeEditModal">
              <div class="modal-content" @click.stop>
                <div class="modal-header">
                  <h3>编辑帖子</h3>
                  <button class="close-btn" @click="closeEditModal">×</button>
                </div>
                <div class="modal-body">
                  <div class="form-group">
                    <label for="editTitle">标题</label>
                    <input 
                      id="editTitle"
                      type="text" 
                      v-model="editForm.title" 
                      class="form-input"
                      placeholder="请输入帖子标题"
                    >
                  </div>
                  <div class="form-group">
                    <label for="editContent">内容</label>
                    <textarea 
                      id="editContent"
                      v-model="editForm.content" 
                      class="form-textarea"
                      placeholder="请输入帖子内容"
                      rows="8"
                    ></textarea>
                  </div>
                </div>
                <div class="modal-footer">
                  <button class="action-btn-sm" @click="closeEditModal">取消</button>
                  <button class="action-btn-sm primary" @click="saveEditedPost">保存</button>
                </div>
              </div>
            </div>
            
            <!-- 创建帖子模态框 -->
            <div v-if="isCreateModalVisible" class="modal-overlay" @click="closeCreateModal">
              <div class="modal-content" @click.stop>
                <div class="modal-header">
                  <h3>创建新帖子</h3>
                  <button class="close-btn" @click="closeCreateModal">×</button>
                </div>
                <div class="modal-body">
                  <div class="form-group">
                    <label for="createTitle">标题</label>
                    <input 
                      id="createTitle"
                      type="text" 
                      v-model="createForm.title" 
                      class="form-input"
                      placeholder="请输入帖子标题"
                    >
                  </div>
                  <div class="form-group">
                    <label for="createAuthor">作者</label>
                    <input 
                      id="createAuthor"
                      type="text" 
                      v-model="createForm.author" 
                      class="form-input"
                      placeholder="请输入作者名称"
                    >
                  </div>
                  <div class="form-group">
                    <label for="createContent">内容</label>
                    <textarea 
                      id="createContent"
                      v-model="createForm.content" 
                      class="form-textarea"
                      placeholder="请输入帖子内容"
                      rows="8"
                    ></textarea>
                  </div>
                </div>
                <div class="modal-footer">
                  <button class="action-btn-sm" @click="closeCreateModal">取消</button>
                  <button class="action-btn-sm primary" @click="createNewPost">创建</button>
                </div>
              </div>
            </div>
  </div>
</template>

<style scoped>
.admin-view {
  min-height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.admin-header {
  background-color: #1890ff;
  color: white;
  padding: 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.15);
  z-index: 100;
}

.admin-header h1 {
  margin: 0;
  font-size: 24px;
}

.admin-info {
  display: flex;
  align-items: center;
  gap: 20px;
}

.logout-btn {
  background-color: rgba(255, 255, 255, 0.2);
  color: white;
  border: 1px solid rgba(255, 255, 255, 0.3);
  padding: 8px 16px;
  border-radius: 4px;
  cursor: pointer;
  transition: all 0.3s;
}

.logout-btn:hover {
  background-color: rgba(255, 255, 255, 0.3);
}

/* 导航菜单样式 */
.admin-nav {
  background-color: white;
  border-bottom: 1px solid #e8e8e8;
  padding: 0 20px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.nav-tabs {
  list-style: none;
  padding: 0;
  margin: 0;
  display: flex;
  gap: 10px;
  overflow-x: auto;
  white-space: nowrap;
}

.nav-tab {
  padding: 15px 20px;
  cursor: pointer;
  display: flex;
  align-items: center;
  gap: 8px;
  transition: all 0.3s;
  border-bottom: 3px solid transparent;
}

.nav-tab:hover {
  background-color: #f0f9ff;
  color: #1890ff;
}

.nav-tab.active {
  color: #1890ff;
  border-bottom-color: #1890ff;
  background-color: #f0f9ff;
  font-weight: 500;
}

.tab-icon {
  font-size: 18px;
}

.tab-text {
  font-size: 14px;
}

.admin-content {
  flex: 1;
  max-width: 1400px;
  margin: 0 auto;
  padding: 20px;
  width: 100%;
}

section {
  margin-bottom: 30px;
}

section h2 {
  color: #333;
  margin-bottom: 20px;
  font-size: 20px;
  border-bottom: 2px solid #e8e8e8;
  padding-bottom: 10px;
}

section h3 {
  color: #555;
  margin: 20px 0 15px;
  font-size: 16px;
}

/* 搜索和过滤样式 */
.search-filter {
  background-color: white;
  padding: 15px;
  border-radius: 8px;
  margin-bottom: 20px;
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
}

.search-input {
  flex: 1;
  min-width: 200px;
  padding: 8px 15px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.search-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.filter-group {
  display: flex;
  align-items: center;
  gap: 10px;
}

.filter-group label {
  font-size: 14px;
  color: #666;
}

.filter-select {
  padding: 8px 15px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  background-color: white;
  cursor: pointer;
  transition: border-color 0.3s;
}

.filter-select:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 统计卡片样式 */
.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 20px;
}

.stat-card {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.stat-icon {
  font-size: 36px;
  width: 60px;
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #f0f9ff;
  border-radius: 50%;
}

.stat-content h3 {
  margin: 0;
  font-size: 28px;
  color: #1890ff;
}

.stat-content p {
  margin: 5px 0 0;
  color: #666;
}

/* 数据表格样式 */
.data-table-wrapper {
  background-color: white;
  border-radius: 8px;
  padding: 20px;
  overflow-x: auto;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #e8e8e8;
}

.data-table th {
  background-color: #fafafa;
  font-weight: 500;
  color: #333;
  font-size: 14px;
}

.data-table td {
  color: #666;
  font-size: 14px;
}

.post-title,
.video-title,
.comment-content {
  max-width: 300px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.comment-content {
  max-width: 250px;
}

/* 状态标签样式 */
.status-badge {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.member,
.status-badge.success {
  background-color: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-badge.active {
  background-color: #e6f7ff;
  color: #1890ff;
  border: 1px solid #91d5ff;
}

.status-badge.inactive {
  background-color: #fff1f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

/* 按钮样式 */
.action-btn {
  background-color: white;
  padding: 25px;
  border-radius: 8px;
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
  font-size: 16px;
  font-weight: 500;
  border: none;
  cursor: pointer;
  transition: all 0.3s;
}

.action-btn.primary {
  color: #1890ff;
  border: 2px solid #1890ff;
}

.action-btn.danger {
  color: #ff4d4f;
  border: 2px solid #ff4d4f;
}

.action-btn.warning {
  color: #faad14;
  border: 2px solid #faad14;
}

.action-btn.success {
  color: #52c41a;
  border: 2px solid #52c41a;
}

.action-btn-sm {
  padding: 6px 12px;
  border-radius: 4px;
  font-size: 12px;
  border: none;
  cursor: pointer;
  margin-right: 8px;
  transition: all 0.3s;
}

.action-btn-sm.primary {
  background-color: #1890ff;
  color: white;
}

.action-btn-sm.primary:hover {
  background-color: #40a9ff;
}

.action-btn-sm.danger {
  background-color: #ff4d4f;
  color: white;
}

.action-btn-sm.danger:hover {
  background-color: #ff7875;
}

.action-btn-sm.warning {
  background-color: #faad14;
  color: white;
}

.action-btn-sm.warning:hover {
  background-color: #ffc53d;
}

.action-btn-sm.success {
  background-color: #52c41a;
  color: white;
}

.action-btn-sm.success:hover {
  background-color: #73d13d;
}

.delete-btn {
  background-color: #ff4d4f;
  color: white;
  border: none;
  padding: 6px 12px;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
  transition: background-color 0.3s;
}

.delete-btn:hover {
  background-color: #ff7875;
}

.action-icon {
  font-size: 32px;
}

/* 操作网格样式 */
.actions-grid,
.operations-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

/* 系统信息样式 */
.info-box {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
}

.info-box p {
  margin: 10px 0;
  color: #333;
}

/* 空状态样式 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  color: #999;
  font-size: 14px;
}

/* 区域标题样式 */
.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 10px;
  border-bottom: 2px solid #e8e8e8;
}

/* 模态框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background-color: white;
  border-radius: 8px;
  width: 90%;
  max-width: 600px;
  max-height: 80vh;
  overflow-y: auto;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.modal-header {
  padding: 20px;
  border-bottom: 1px solid #e8e8e8;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.close-btn {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 30px;
  height: 30px;
  display: flex;
  align-items: center;
  justify-content: center;
  border-radius: 4px;
  transition: all 0.3s;
}

.close-btn:hover {
  background-color: #f5f5f5;
  color: #333;
}

.modal-body {
  padding: 20px;
}

.form-group {
  margin-bottom: 20px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  font-size: 14px;
  color: #666;
}

.form-input,
.form-textarea {
  width: 100%;
  padding: 10px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  transition: border-color 0.3s;
}

.form-input:focus,
.form-textarea:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

.form-textarea {
  resize: vertical;
}

.modal-footer {
  padding: 20px;
  border-top: 1px solid #e8e8e8;
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}

/* 美化框样式 */
.clickable-box {
  background-color: #ffffff;
  border: 2px solid #e0e0e0;
  border-radius: 12px;
  transition: all 0.3s ease;
  cursor: pointer;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
}

.clickable-box:hover {
  border-color: #1890ff;
  box-shadow: 0 4px 12px rgba(24, 144, 255, 0.1);
  transform: translateY(-2px);
}

.clickable-box.danger:hover {
  border-color: #ff4d4f;
  box-shadow: 0 4px 12px rgba(255, 77, 79, 0.1);
}

.clickable-box.warning:hover {
  border-color: #faad14;
  box-shadow: 0 4px 12px rgba(250, 173, 20, 0.1);
}

.clickable-box.success:hover {
  border-color: #52c41a;
  box-shadow: 0 4px 12px rgba(82, 196, 26, 0.1);
}

.clickable-box:active {
  transform: translateY(0);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .admin-content {
    padding: 10px;
  }
  
  .stats-grid,
  .actions-grid,
  .operations-grid {
    grid-template-columns: 1fr;
  }
  
  .search-filter {
    flex-direction: column;
    align-items: stretch;
  }
  
  .search-input {
    min-width: auto;
  }
  
  .data-table-wrapper {
    padding: 10px;
  }
  
  .data-table th,
  .data-table td {
    padding: 8px;
    font-size: 12px;
  }
}
</style>